<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
<!--      <el-form-item label="订单编号" prop="orderNumber">-->
<!--        <el-input-->
<!--            v-model="queryParams.orderNumber"-->
<!--            placeholder="请输入订单编号"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="客户名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="订单总金额" prop="totalAmount">-->
<!--        <el-input-->
<!--            v-model="queryParams.totalAmount"-->
<!--            placeholder="请输入订单总金额"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="收货地址" prop="shippingAddress">-->
<!--        <el-input-->
<!--            v-model="queryParams.shippingAddress"-->
<!--            placeholder="请输入收货地址"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="期望发货日期" style="width: 308px">
        <el-date-picker
            v-model="daterangeExpectedDeliveryDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="实际发货日期" style="width: 308px">-->
<!--        <el-date-picker-->
<!--            v-model="daterangeActualDeliveryDate"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            type="daterange"-->
<!--            range-separator="-"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item label="取消操作人" prop="canceledBy">
        <el-input
            v-model="queryParams.canceledBy"
            placeholder="请输入取消操作人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="创建人" prop="createdBy">-->
<!--        <el-input-->
<!--            v-model="queryParams.createdBy"-->
<!--            placeholder="请输入创建人"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建时间" prop="createdAt">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.createdAt"-->
<!--                        type="date"-->
<!--                        value-format="YYYY-MM-DD"-->
<!--                        placeholder="请选择创建时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="修改时间" prop="updatedAt">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.updatedAt"-->
<!--                        type="date"-->
<!--                        value-format="YYYY-MM-DD"-->
<!--                        placeholder="请选择修改时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['SysSales:SysSalesOrders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['SysSales:SysSalesOrders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['SysSales:SysSalesOrders:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysSalesOrdersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNumber" :show-overflow-tooltip="true"/>
      <el-table-column label="客户名称" align="center" prop="customerName" :show-overflow-tooltip="true"/>
      <el-table-column label="订单总金额" align="center" prop="totalAmount" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="订单状态" align="center" prop="status" /> -->
       <el-table-column label="订单状态" align="center" prop="status":show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center" prop="shippingAddress" :show-overflow-tooltip="true"/>
      <el-table-column label="发货日期" align="center" width="240">
        <template #default="scope">
          <div>
            <span>期望发货日期: {{ parseTime(scope.row.expectedDeliveryDate, '{y}-{m}-{d}') }}</span><br/>
            <span>实际发货日期: {{ parseTime(scope.row.actualDeliveryDate, '{y}-{m}-{d}') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="取消原因" align="center" prop="canceledReason" />
      <el-table-column label="取消操作人" align="center" prop="canceledUserName" />
<!--      <el-table-column label="创建人" align="center" prop="createdUserName" />-->
<!--      <el-table-column label="时间" align="center" width="240">-->
<!--        <template #default="scope">-->
<!--          <div>-->
<!--            <span>创建时间: {{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span><br/>-->
<!--            <span>修改时间: {{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="状态管理" align="center" class-name="small-padding fixed-width">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" icon="Finished" @click="handleFinished(scope.row)" v-hasPermi="['SysSales:SysSalesOrders:Finished']">完成</el-button>-->
<!--          <el-button link type="primary" icon="Cancle" @click="handleCancel(scope.row)" v-hasPermi="['SysSales:SysSalesOrders:Cancle']">取消订单</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysSales:SysSalesOrders:edit']">修改</el-button>
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" style="margin-left: 2px" v-hasPermi="['SysSales:SysSalesOrders:query']">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" style="margin-left: 2px" v-hasPermi="['SysSales:SysSalesOrders:remove']">删除</el-button>
          <el-dropdown trigger="click">
<!--            <span class="el-dropdown-link">订单状态<el-icon><ArrowDown /></el-icon></span>-->
            <el-button link type="primary" icon="DArrowRight">订单状态</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="Finished" @click="handleFinished(scope.row)" v-hasPermi="['SysSales:SysSalesOrders:Finished']">完成</el-dropdown-item>
                <el-dropdown-item icon="CloseBold" @click="handleCancel(scope.row)" v-hasPermi="['SysSales:SysSalesOrders:Cancle']">取消订单</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 取消卡片弹窗 -->
    <el-dialog v-model="showCancelCard" title="取消订单" width="400px">
      <el-form label-width="80px">
        <el-form-item label="取消原因">
          <el-input v-model="cancelReason" placeholder="请输入取消原因"></el-input>
        </el-form-item>
<!--        <el-form-item label="取消操作人">-->
<!--          <el-input v-model="canceledBy" placeholder="请输入取消操作人"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      
      <template #footer>
        <el-button @click="showCancelCard = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitCancel">确定</el-button>
      </template>
    </el-dialog>


    <!-- 添加或修改订单主表对话框 -->
    <el-dialog :title="title" v-model="open" width="790px" append-to-body>
      <el-form ref="SysSalesOrdersRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户" @change="handleCustomerChange" :disabled="disabled">
            <el-option 
              v-for="item in customerOptions" :key="item.customerId" :label="item.name" :value="item.customerId"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input v-model="form.shippingAddress" placeholder="请输入收货地址"  :disabled="disabled"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
        <el-form-item label="期望发货日期">
              <el-date-picker clearable
                              v-model="form.expectedDeliveryDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              :disabled="disabled"
                              placeholder="请选择期望发货日期"
              >
              </el-date-picker>
        </el-form-item>
          </el-col>
            <el-col :span="12">
            <el-form-item label="实际发货日期" v-if="isViewMode">
              <el-date-picker clearable
                              v-model="form.actualDeliveryDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              :disabled="disabled"
                              placeholder="请选择期望发货日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="订单状态" prop="status">
          <span>{{ getStatusText(form.status) }}</span>
        </el-form-item>

        <el-divider content-position="center">订单明细表信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" size="small" @click="handleAddSysSalesOrderDetails" v-if="!isViewMode">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" size="small" @click="handleDeleteSysSalesOrderDetails" v-if="!isViewMode">删除</el-button>
          </el-col>
        </el-row>
        <!--订单明细表信息-->
        <el-table :data="sysSalesOrderDetailsList" :row-class-name="rowSysSalesOrderDetailsIndex" @selection-change="handleSysSalesOrderDetailsSelectionChange" ref="sysSalesOrderDetails">
<!--          <el-table-column type="selection" width="50" align="center" :disabled="disabled" />-->
          <el-table-column width="50" align="center">
            <template #default="scope">
              <el-checkbox v-model="scope.row.checked" :disabled="disabled" />
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="产品名称" align="center" prop="name" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.productId"
                placeholder="请选择产品名称"
                @change="handleNameChange"
                clearable
                filterable
                remote
                :disabled="disabled"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.productId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="购买数量" align="center" prop="quantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入购买数量" :disabled="disabled" />
            </template>
          </el-table-column>
          <el-table-column label="成交单价" align="center" prop="unitPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.unitPrice" placeholder="请输入成交单价" :disabled="disabled"/>
            </template>
          </el-table-column>
          <!--          <el-table-column label="小计金额" prop="subtotal" width="150">-->
          <!--            <template #default="scope">-->
          <!--              <el-input v-model="scope.row.subtotal" placeholder="请输入小计金额" />-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="修改时间" align="center" prop="createdAt" width="200" >
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.createdAt"
                              type="date"
                              style="width: 150px"
                              value-format="YYYY-MM-DD"
                              :disabled="disabled"
                              placeholder="请选择修改时间">
              </el-date-picker>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysSalesOrders">
import { listSysSalesOrders, getSysSalesOrders, delSysSalesOrders, addSysSalesOrders, updateSysSalesOrders } from "@/api/SysSales/SysSalesOrders"
import { customRef } from "vue"
import {listSysSalesProducts} from "@/api/SysSales/SysSalesProducts"
import { listSysSalesCustomers } from "@/api/SysSales/SysSalesCustomers"
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
import { ref } from 'vue'
const SysSalesOrdersList = ref([])
const sysSalesOrderDetailsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedSysSalesOrderDetails = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const isViewMode = ref(false)
const disabled = ref(false)
const daterangeExpectedDeliveryDate = ref([])
const daterangeActualDeliveryDate = ref([])
const customerOptions = ref([])
const showCancelCard = ref(false) // 控制取消卡片的显示
const cancelReason = ref('')
const canceledBy = ref('')
//const row = ref(null) // 用于保存当前操作的订单行
const row = ref({}) // 在 script setup 顶部声明
const shippingAddress = ref('')
const productOptions = ref([])
const quantity= ref(1)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerName: null,
    orderNumber: null,
    customerId: null,
    totalAmount: null,
    status: null,
    shippingAddress: null,
    expectedDeliveryDate: null,
    actualDeliveryDate: null,
    canceledReason: null,
    canceledBy: null,
    createdBy: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    orderNumber: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    customerId: [
      { required: true, message: "客户信息不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "订单总金额不能为空", trigger: "blur" }
    ],
    createdBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "购买数量不能为空", trigger: "blur" }
    ],
    unitPrice: [
      { required: true, message: "成交单价不能为空", trigger: "blur" }
    ],
    shippingAddress: [
      { required: true, message: "收货地址不能为空", trigger: "blur" }
    ],
    expectedDeliveryDate: [
      { required: true, message: "预计发货时间不能为空", trigger: "blur" }
    ],
    sysSalesOrderDetailsList: [
      { required: true, message: "请至少添加一条订单明细", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单主表列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeExpectedDeliveryDate && '' != daterangeExpectedDeliveryDate) {
    queryParams.value.params["beginExpectedDeliveryDate"] = daterangeExpectedDeliveryDate.value[0]
    queryParams.value.params["endExpectedDeliveryDate"] = daterangeExpectedDeliveryDate.value[1]
  }
  if (null != daterangeActualDeliveryDate && '' != daterangeActualDeliveryDate) {
    queryParams.value.params["beginActualDeliveryDate"] = daterangeActualDeliveryDate.value[0]
    queryParams.value.params["endActualDeliveryDate"] = daterangeActualDeliveryDate.value[1]
  }
  listSysSalesOrders(queryParams.value).then(response => {
    SysSalesOrdersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 新增：获取产品列表
function getproductOptions() {
  listSysSalesProducts({ pageNum: 1, pageSize: 1000 }).then(response => {
    productOptions.value = response.rows
  })
}

// 修改 onMounted 钩子，同时加载客户和产品数据
onMounted(() => {
  getcustomerOptions()
  getproductOptions() // 添加产品数据加载
})

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNumber: null,
    customerId: null,
    totalAmount: 0,
    status: null,
    shippingAddress: null,
    expectedDeliveryDate: null,
    actualDeliveryDate: null,
    canceledReason: null,
    canceledBy: null,
    createdBy: null,
    createdAt: null,
    updatedAt: null
  }
  sysSalesOrderDetailsList.value = []
  proxy.resetForm("SysSalesOrdersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeExpectedDeliveryDate.value = []
  daterangeActualDeliveryDate.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  isViewMode.value = false
  disabled.value = false
  open.value = true
  title.value = "添加订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  isViewMode.value = false
  disabled.value = false
  const _orderId = row.orderId || ids.value
  getSysSalesOrders(_orderId).then(response => {
    form.value = response.data
    sysSalesOrderDetailsList.value = response.data.sysSalesOrderDetailsList
    open.value = true
    title.value = "修改订单"
  })
}
/** 详情按钮操作 */
function handleView (row){
  reset()
  disabled.value = true
  isViewMode.value = true
  getSysSalesOrders(row.orderId).then(response => {
    form.value = response.data
    sysSalesOrderDetailsList.value = response.data.sysSalesOrderDetailsList
    open.value = true
    title.value = "订单详情"
  })
}
const statusMap = {
  completed: '已完成',
  canceled: '已取消',
  pending: '待处理'
}
// 计算属性，根据订单的状态显示中文
const getStatusText = (status) => {
  return statusMap[status] || '未知状态';
}
//完成订单
const handleFinished = (row) => {
  //console.log('更新数据:', data) // 打印发送的数据
  // 防止重复完成
  if (row.status === 'completed') {
    proxy.$modal.msgWarning("该订单已完成，无需重复操作")
    return
  }

  // 防止已取消订单操作
  if (row.status === 'canceled') {
    proxy.$modal.msgWarning("已取消的订单不可操作")
    return
  }

  proxy.$modal.confirm(`是否确认将订单 "${row.orderNumber}" 标记为完成？`).then(() => {
    const data = { ...row, status: 'completed' }

    updateSysSalesOrders(data).then(() => {
      proxy.$modal.msgSuccess("订单已标记为完成")
      getList() // 刷新列表
    }).catch(() => {
      proxy.$modal.msgError("操作失败，请重试")
    })
  }).catch(() => {
    // 用户取消
  })
}

// 取消按钮点击事件
const handleCancel = (orderRow) => {
  if (!orderRow || !orderRow.orderId) {
    proxy.$modal.msgError("无效的订单信息");
    return;
  }

  // 判断订单是否已完成，如果已完成则不允许取消
  if (orderRow.status === 'completed') {
    proxy.$modal.msgWarning("订单已完成，不可取消");
    return;
  }

  showCancelCard.value = true;
  cancelReason.value = "";
  canceledBy.value = "";
  row.value = orderRow; // 安全赋值
}

// 提交取消信息
const handleSubmitCancel = () => {
  console.log('取消信息:', {
    cancelReason: cancelReason.value,
    canceledBy: canceledBy.value
  })
  if (!cancelReason.value ) {
    proxy.$modal.msgWarning("取消原因不能为空");
    return;
  }

  // 只提交需要修改的字段：状态、取消原因和操作人
  const data = {
    orderId: row.value.orderId, // 当前订单的ID
    status: 'canceled', // 更新状态为已取消
    canceledReason: cancelReason.value, // 取消原因
    canceledBy: useUserStore().id, // 使用当前登录用户ID
  };

  // 复用原来的 updateSysSalesOrders 方法，提交数据
  updateSysSalesOrders(data).then(() => {
    showCancelCard.value = false; // 关闭取消卡片
    proxy.$modal.msgSuccess("订单取消成功");
    getList(); // 刷新订单列表
  }).catch(() => {
    proxy.$modal.msgError("操作失败，请重试");
  });
}
//自动填充收货地址
const handleCustomerChange = (value) => {
  if (value) {
    // 获取客户信息
    listSysSalesCustomers({ pageNum: 1, pageSize: 1, customerId: value }).then(response => {
      console.log('客户信息响应:', response)
      if (response.rows && response.rows.length > 0) {
        const customer = response.rows[0]
        // 组合完整地址：省份+城市+区县+详细地址
        const province = customer.province || ''
        const city = customer.city || ''
        const district = customer.district || ''
        const addressDetail = customer.address || '' // 使用address字段

        // 拼接完整地址
        const fullAddress = [province, city, district, addressDetail].filter(Boolean).join(' ')
        console.log('填充的收货地址:', fullAddress) // 调试用

        // 确保响应式更新
        form.value.shippingAddress = fullAddress
      }
    }).catch(error => {
      console.error('获取客户信息失败:', error)
    })
  }
}

function getcustomerOptions(){
  listSysSalesCustomers({ pageNum: 1, pageSize: 1000}).then(response => {
    customerOptions.value = response.rows
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysSalesOrdersRef"].validate(valid => {
    if (valid) {
      // 校验订单明细中的 quantity 和 unitPrice
      const invalidItems = sysSalesOrderDetailsList.value.filter(item => {
        const qty = parseFloat(item.quantity)
        const price = parseFloat(item.unitPrice)

        // 检查是否为有效数字且 >= 0
        const isQtyValid = !isNaN(qty) && qty >= 0
        const isPriceValid = !isNaN(price) && price >= 0

        return !isQtyValid || !isPriceValid
      })

      if (invalidItems.length > 0) {
        proxy.$modal.msgError("购买数量和成交单价必须为大于等于0的数字")
        return
      }
      // 传递明细数据
      form.value.sysSalesOrderDetailsList = sysSalesOrderDetailsList.value
      if (form.value.orderId != null) {
        updateSysSalesOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysSalesOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除订单主表编号为"' + _orderIds + '"的数据项？').then(function() {
    return delSysSalesOrders(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 订单明细表序号 */
function rowSysSalesOrderDetailsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 订单明细表添加按钮操作 */
function handleAddSysSalesOrderDetails() {
  let obj = {}
  obj.productId = ""
  obj.name = ""
  obj.unitPrice = ""
  obj.subtotal = ""
  obj.createdAt = ""
  obj.checked = false
  sysSalesOrderDetailsList.value.push(obj)
}

/** 订单明细表删除按钮操作 */
function handleDeleteSysSalesOrderDetails() {
  if (checkedSysSalesOrderDetails.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的订单明细表数据")
  } else {
    const sysSalesOrderDetailss = sysSalesOrderDetailsList.value
    const checkedSysSalesOrderDetailss = checkedSysSalesOrderDetails.value
    sysSalesOrderDetailsList.value = sysSalesOrderDetailss.filter(function(item) {
      return checkedSysSalesOrderDetailss.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleSysSalesOrderDetailsSelectionChange(selection) {
  checkedSysSalesOrderDetails.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysSales/SysSalesOrders/export', {
    ...queryParams.value
  }, `SysSalesOrders_${new Date().getTime()}.xlsx`)
}
onMounted(() => {
  getcustomerOptions()
})
getList()
</script>


